package com.cc.eds;

import com.cc.eds.model.DataInfo;
import com.cc.eds.model.Eds;
import com.cc.eds.model.EdsDataXml;
import com.cc.eds.model.GlobalData;
import com.cc.eds.process.DefaultEdsRead;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import lombok.Getter;
import lombok.Setter;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * @author Administrator
 */
public class MainController implements Initializable {

    public ComboBox<ComboBoxItem> category;
    public TableView<Map<String, String>> dataTable;
    public Label bcpFileName;
    public Label fileName;
    public Label dataCount;
    public Button openFile;

    private DefaultEdsRead defaultEdsRead;
    @Getter
    @Setter
    private Stage stage;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initComboBox();
    }

    private void initComboBox() {
        category.getSelectionModel().selectFirst();
        category.setTooltip(new Tooltip("选择查看内容"));
        // 设置下拉框的选择监听器
        category.getSelectionModel().selectedItemProperty().addListener((arg0, oldCbi, newCbi) -> {
            // getSelectedIndex方法可获得选中项的序号，getSelectedItem方法可获得选中项的对象
            viewDataTable(newCbi);
        });
        category.setDisable(true);
    }

    private void setCategoryItems(List<ComboBoxItem> categoryItems) {
        ObservableList<ComboBoxItem> observableList = FXCollections.observableArrayList(categoryItems);
        category.setItems(observableList);
        ComboBoxItem selectedItem = category.getSelectionModel().getSelectedItem();
        viewDataTable(selectedItem);
    }

    private void viewDataTable(ComboBoxItem cbi) {
        if (this.defaultEdsRead == null) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("提示");
            alert.setHeaderText(null);
            alert.setContentText("请先打开电子数据包");
            alert.show();
            return;
        }
        dataTable.getItems().clear();
        if (cbi == null) {
            return;
        }
        List<Map<String, String>> read = this.defaultEdsRead.read(this.defaultEdsRead.getDestPath(), cbi.getVal());
        if (read == null) {
            // 弹出消息框
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("提示");
            alert.setHeaderText(null);
            alert.setContentText("[" + cbi.getText() + "]下暂无数据");
            alert.show();
        } else {
            List<TableColumn<Map<String, String>, String>> columns = getTableColumns(read);
            dataTable.getColumns().setAll(columns);
            dataTable.setItems(FXCollections.observableArrayList(read));
        }
    }

    private List<TableColumn<Map<String, String>, String>> getTableColumns(List<Map<String, String>> read) {
        Map<String, String> firstData = read.get(0);
        List<TableColumn<Map<String, String>, String>> columns = new ArrayList<>();
        firstData.forEach((key, value) -> {
            TableColumn<Map<String, String>, String> categoryCol = new TableColumn<>(key);
            categoryCol.setCellValueFactory(param -> new SimpleStringProperty(param.getValue().get(key)));
            columns.add(categoryCol);
        });
        return columns;
    }

    public void openFile(ActionEvent actionEvent) {
        FileChooser fileChooser = new FileChooser();
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("zip files (*.zip)", "*.zip");
        fileChooser.getExtensionFilters().add(extFilter);
        File file = fileChooser.showOpenDialog(this.stage);
        try {
            if (file != null) {
                this.fileName.setText("数据加载中....");
                this.openFile.setDisable(true);
                this.category.setDisable(true);
                Task<DefaultEdsRead> task = new Task<>() {
                    @Override
                    protected DefaultEdsRead call() throws Exception {
                        return new DefaultEdsRead(file);
                    }
                };
                task.setOnSucceeded(event -> {
                    this.defaultEdsRead = task.getValue();
                    this.defaultEdsRead.setBcpFileNameLabel(bcpFileName.textProperty());
                    this.defaultEdsRead.setDataCountLabel(dataCount.textProperty());
                    List<ComboBoxItem> categoryItems = new ArrayList<>();
                    EdsDataXml edsDataXml = this.defaultEdsRead.getEdsDataXml();
                    for (DataInfo dataInfo : edsDataXml.getDataInfoListBySort()) {
                        String tabName = dataInfo.getValByIk(Eds.TABLE_NAME_IK);
                        if (GlobalData.CATEGORY_DATA.containsKey(tabName)) {
                            categoryItems.add(GlobalData.CATEGORY_DATA.get(tabName));
                        }
                    }
                    setCategoryItems(categoryItems);
                    this.fileName.setText("当前数据包" + file.getName());
                    this.openFile.setDisable(false);
                    this.category.setDisable(false);
                });
                new Thread(task).start();
            }
        } catch (Exception e) {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("提示");
            alert.setHeaderText(null);
            alert.setContentText("打开文件错误");
            alert.show();
        }
    }
}